/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    stm32f3xx_it.c
  * @brief   Interrupt Service Routines.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f3xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "bsp.h"

#include "SEGGER_RTT.h"
#include "SEGGER_RTT_Conf.h"
/* USER CODE END Includes */


/* External variables --------------------------------------------------------*/
extern CAN_HandleTypeDef hcan;
extern TIM_HandleTypeDef htim1;
extern TIM_HandleTypeDef htim15;
extern TIM_HandleTypeDef htim16;
extern DMA_HandleTypeDef hdma_usart2_rx;
extern DMA_HandleTypeDef hdma_usart2_tx;
extern UART_HandleTypeDef huart2;
extern TIM_HandleTypeDef htim3;

extern unsigned char g_motor_sport;
extern unsigned char g_encoder_read_trigger;

extern unsigned char initial;

/// @brief
/// @param  
void NMI_Handler(void)
{
   while (1)
  {
  }
}

/// @brief 
/// @param  
void HardFault_Handler(void)
{
  while (1)
  {
  }
}

/// @brief 
/// @param  
void MemManage_Handler(void)
{
  while (1)
  {
  }
}

/// @brief 
/// @param  
void BusFault_Handler(void)
{
  while (1)
  {
  }
}

/// @brief 
/// @param  
void UsageFault_Handler(void)
{
  while (1)
  {
  }
}

/// @brief 
/// @param  
void SVC_Handler(void)
{
}

/// @brief 
/// @param  
void DebugMon_Handler(void)
{
}

/// @brief 
/// @param  
void PendSV_Handler(void)
{
}

/// @brief 
/// @param  
void SysTick_Handler(void)
{
  HAL_IncTick();
}

/// @brief 
/// @param  
void DMA1_Channel6_IRQHandler(void)
{
  HAL_DMA_IRQHandler(&hdma_usart2_rx);
}

/// @brief 
/// @param  
void DMA1_Channel7_IRQHandler(void)
{
  HAL_DMA_IRQHandler(&hdma_usart2_tx);
}

/// @brief 
/// @param  
void USB_HP_CAN_TX_IRQHandler(void)
{
  HAL_CAN_IRQHandler(&hcan);
}


extern MotorState motor_state;

/// @brief 
/// @param  
void USB_LP_CAN_RX0_IRQHandler(void)
{
  CAN_RxHeaderTypeDef RxHeader;
  uint8_t RxData[8];

  if (HAL_CAN_GetRxMessage(&hcan, CAN_RX_FIFO0, &RxHeader, RxData) == HAL_OK)
  {
    SEGGER_RTT_CustomFunction(1, 
															0, 
															"Received CAN ID: 0x%X, Data: %02X %02X %02X %02X %02X %02X %02X %02X\n",
                              RxHeader.StdId, 
															RxData[0], 
															RxData[1], 
															RxData[2], 
															RxData[3],
                              RxData[4], 
															RxData[5], 
															RxData[6], 
															RxData[7]);
		
		//number
		switch(RxData[0])
		{
			case MOTOR_STALLED:
				g_motor_sport = MOTOR_STALLED;
				break;

			case MOTOR_EMESTOP:
				g_motor_sport = MOTOR_EMESTOP;
				break;
			
			case MOTOR_ROTATION:
				motor_state = MOTOR_CLOCKWISE;
				g_motor_sport = MOTOR_ROTATION;
        initial = 1;
				break;
			
			default:
				break;
		}
  }
  HAL_CAN_IRQHandler(&hcan);
}

/// @brief 
/// @param  
void CAN_RX1_IRQHandler(void)
{
  HAL_CAN_IRQHandler(&hcan);
}

/// @brief 
/// @param  
void CAN_SCE_IRQHandler(void)
{
  HAL_CAN_IRQHandler(&hcan);
}

/// @brief 
/// @param  
void EXTI9_5_IRQHandler(void)
{
  HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_6);
  HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_7);
  HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_8);
}

/// @brief 
/// @param  
void EXTI15_10_IRQHandler(void)
{
  HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_15);
}

/// @brief 
/// @param  
void TIM1_BRK_TIM15_IRQHandler(void)
{
  HAL_TIM_IRQHandler(&htim1);
  HAL_TIM_IRQHandler(&htim15);
}

/// @brief 
/// @param  
void TIM1_UP_TIM16_IRQHandler(void)
{
  HAL_TIM_IRQHandler(&htim1);
  HAL_TIM_IRQHandler(&htim16);
}

/// @brief 
/// @param  
void USART2_IRQHandler(void)
{
	BSP_UART_IDLE_Handler(&huart2);
  HAL_UART_IRQHandler(&huart2);
}

/// @brief 
/// @param  
void EXTI0_IRQHandler(void)
{
  HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0);
}

/// @brief 
/// @param  
void TIM3_IRQHandler(void)
{
  HAL_TIM_IRQHandler(&htim3);
}

 /**
   * @brief  SysTick中断回调函数
   * @param  无
   * @retval 无
   */
 void HAL_SYSTICK_Callback(void)
 {
   static uint16_t i = 0;

   i++;
   if(i == 100)/* 100ms计算一次 */
   {
//     /* 电机旋转方向 = 计数器计数方向 */
//     Motor_Direction = __HAL_TIM_IS_TIM_COUNTING_DOWN(&htim3);

//     /* 当前时刻总计数值 = 计数器值 + 计数溢出次数 * 计数器溢出值  */
//     Capture_Count =__HAL_TIM_GET_COUNTER(&htim3) + (Encoder_Overflow_Count * ENCODER_TIM_PERIOD);

//     /* 转轴转速 = 单位时间内的计数值 / 编码器总分辨率 * 时间系数  */
//     Shaft_Speed = (float)(Capture_Count - Last_Count) / ENCODER_TOTAL_RESOLUTION * 10 ;

//     printf("电机方向：%d\r\n", Motor_Direction);
//     printf("单位时间内有效计数值：%d\r\n", Capture_Count - Last_Count);/* 单位时间计数值 = 当前时刻总计数值 - 上一时刻总计数值 */
//     printf("电机转轴处转速：%.2f 转/秒 \r\n", Shaft_Speed);
//     printf("电机输出轴转速：%.2f 转/秒 \r\n", Shaft_Speed/REDUCTION_RATIO);/* 输出轴转速 = 转轴转速 / 减速比 */

//     /* 记录当前总计数值，供下一时刻计算使用 */
//     Last_Count = Capture_Count;
		 
		 SEGGER_RTT_printf(0, "SEGGER_RTT_GetKey \r\n");	
     i = 0;
   }
 }

extern uint8_t uc_motor_angle[8]; // 初始化为0
/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM4 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  /* USER CODE BEGIN Callback 1 */
	if(htim->Instance == TIM16)
  {
		HAL_GPIO_TogglePin(LED3_GPIO_Port, LED3_Pin);
		HAL_GPIO_TogglePin(LED4_GPIO_Port, LED4_Pin);
    CAN_SendMessage(&hcan, 0x0b, uc_motor_angle, 8); // 注意这里的 CAN ID 变量名要和你项目中的一致
		g_encoder_read_trigger = 1;
		if(starter_motor == 1)
    {
			//HAL_GPIO_TogglePin(MBW_GPIO_Port, MBW_Pin);
			HAL_GPIO_TogglePin(MFW_GPIO_Port, MFW_Pin);		
		}
		else if(starter_motor == 0)
		{
			HAL_GPIO_WritePin(MFW_GPIO_Port, MFW_Pin, GPIO_PIN_RESET);
			//HAL_GPIO_TogglePin(MBW_GPIO_Port, MBW_Pin);
			//HAL_GPIO_TogglePin(MFW_GPIO_Port, MFW_Pin);			
		}
	}
  else if(htim->Instance == TIM3)
  {
   /* 判断当前计数器计数方向 */
   if(__HAL_TIM_IS_TIM_COUNTING_DOWN(&htim3))
   {
     /* 下溢 */
     Encoder_Overflow_Count--;	
		 //SEGGER_RTT_printf(0, "1. Encoder_Overflow_Count = %d \r\n" , Encoder_Overflow_Count);
	 }
   else
   {
		/* 上溢 */
		Encoder_Overflow_Count++;		
		//SEGGER_RTT_printf(0, "2. Encoder_Overflow_Count = %d \r\n", Encoder_Overflow_Count);
	 }
	}
}



/// @brief //mark 硬件中断
/// @param GPIO_Pin 
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) 
{
    if (GPIO_Pin == HALL_A_PIN || GPIO_Pin == HALL_B_PIN || GPIO_Pin == HALL_C_PIN) 
    { 
			hall_changed = 1;
    }
    else if (GPIO_Pin == GPIO_PIN_15)
    {      
        static unsigned char timeloop = 0;  
        __HAL_TIM_SET_COUNTER(&htim3, 0);//将定时器硬件计数器清零
        Encoder_Overflow_Count = 0;
        last_count = 0; // 将用于计算速度的 last_count 也清零，避免产生一个巨大的速度跳变   
				timeloop++;
        SEGGER_RTT_SetTerminal(1);
        SEGGER_RTT_printf(0, "timeloop = %d , Z-Phase Detected! Encoder has been reset to zero.\n" , timeloop);    
    
    }
}

/// @brief 
/// @param huart 
void BSP_UART_IDLE_Handler(UART_HandleTypeDef *huart)
{
	unsigned int rxCnt = 0;
	if(__HAL_UART_GET_IT_SOURCE(huart, UART_IT_IDLE) != RESET)/* 开启了空闲中断位才进入判断 */
	{
		
		if(__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) != RESET)/* 是空闲中断 */
		{	
			__HAL_UART_CLEAR_IDLEFLAG(huart);	/* 清除串口空闲中断 */
			unsigned char dmaBit = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR);
			if(dmaBit)
			{		
				rxCnt = __HAL_DMA_GET_COUNTER(huart->hdmarx);/* 从DMA寄存器中读取剩余空间寄存器值 */
			}
			else
			{
				rxCnt = huart->RxXferCount;
			}		
			HAL_UART_AbortReceive(huart);/* 关闭串口接收 */
			
			/* 串口1中断 */
			if(huart->Instance == USART1)
			{
//				g_tBspUart1.rxLen  = g_tBspUart1.rxSize - rxCnt;
//				g_tBspUart1.rxFlag = 1;
//				
//				osEventFlagsSet(event_USART1_ID , 0x01U << 0);  /*启动事件标志组 event_Flags1的flag0置1*/				
//				/* 重新开启串口接收 如果在中断里面开启接收，发送函数需要开关中断,具体原因请看文档UART里面关于 __HAL_LCOK 说明 */
//				if(dmaBit)
//				{
//					HAL_UART_Receive_DMA(&huart1 , g_tBspUart1.pRxBuf , g_tBspUart1.rxSize);
//				}
//				else
//				{
//					HAL_UART_Receive_IT(&huart1 , g_tBspUart1.pRxBuf , g_tBspUart1.rxSize);
//				}
			}
			
			else if(huart->Instance == USART2)
			{//
				g_tBspUart2.rxLen  = g_tBspUart2.rxSize - rxCnt;
				g_tBspUart2.rxFlag = 1;
				//osEventFlagsSet(event_USART2_ID , 0x01U << 0);  /*启动事件标志组 event_Flags1的flag0置1*/				
				/* 重新开启串口接收 如果在中断里面开启接收，发送函数需要开关中断,具体原因请看文档UART里面关于 __HAL_LCOK 说明 */
				if(dmaBit)
				{
					HAL_UART_Receive_DMA(&huart2 , g_tBspUart2.pRxBuf , g_tBspUart2.rxSize);
				}
				else
				{
					HAL_UART_Receive_IT(&huart2 , g_tBspUart2.pRxBuf , g_tBspUart2.rxSize);
				}
			}						
		}
	}
}
/* USER CODE END 1 */
